﻿// <copyright file="XmlHelper.cs" company="Snowman Consulting">
//     Copyright (c) 2009 Snowman Consulting. All rights reserved.
// </copyright>

namespace SnowmanConsulting.ProductKeyManager.Xml
{
    using System;
    using System.IO;
    using System.Text;
    using System.Xml.Linq;

    /// <summary>
    /// A static class to help with XML tasks.
    /// </summary>
    public static class XmlHelper
    {
        /// <summary>
        /// Loads the XML from a file.
        /// </summary>
        /// <param name="fileUri">The file URI.</param>
        /// <returns>A IXmlHandler</returns>
        public static IXmlHandler Load(Uri fileUri)
        {
            XDocument xmlDocument = XDocument.Load(fileUri.ToString());
            return XmlHelper.Load(xmlDocument);
        }

        /// <summary>
        /// Imports the XML.
        /// </summary>
        /// <param name="xml">The XML file.</param>
        /// <returns>A IXmlHandler</returns>
        public static IXmlHandler Load(string xml)
        {
            XDocument xmlDocument = XDocument.Load(new StringReader(xml));
            return XmlHelper.Load(xmlDocument);
        }

        /// <summary>
        /// Loads the specified XML document.
        /// </summary>
        /// <param name="xmlDocument">The XML document.</param>
        /// <returns>A IXmlHandler</returns>
        public static IXmlHandler Load(XDocument xmlDocument)
        {
            IXmlHandler handler;

            handler = new ProductKeyManagerXmlHandler();
            handler.Load(xmlDocument);

            if (handler.Products.Count > 0)
            {
                return handler;
            }

            handler = new MsdnXmlHandler();
            handler.Load(xmlDocument);

            if (handler.Products.Count > 0)
            {
                return handler;
            }

            handler = new XamlHandler();
            handler.Load(xmlDocument);

            if (handler.Products.Count > 0)
            {
                return handler;
            }

            return null;
        }

        /// <summary>
        /// Saves the product key XML.
        /// </summary>
        /// <param name="generateStyleSheet">if set to <c>true</c> [generate style sheet].</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="xml">The XML to output.</param>
        /// <param name="xmlStyleSheet">The XML style sheet.</param>
        public static void SaveProductKeyXml(bool generateStyleSheet, string fileName, string xml, string xmlStyleSheet)
        {
            File.WriteAllText(fileName, xml, Encoding.Default);
            if (generateStyleSheet)
            {
                File.WriteAllText(fileName + ".xsl", xmlStyleSheet, Encoding.Default);
            }
        }
    }
}
